package org.galaxyworld.flycode.utils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.*;

public class OutputFileUtils {

    private static String createPackageDirs(String outputDir, String packageName) {
        String dirs = StringUtils.replace(packageName, ".", "/");
        String targetDirPath = FilenameUtils.normalize(String.format("%s/%s", outputDir, dirs));
        File targetDir = new File(targetDirPath);
        if (!targetDir.exists()) {
            try {
                FileUtils.forceMkdir(new File(targetDirPath));
                return targetDirPath;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        } else {
            return targetDirPath;
        }
    }

    public static Writer createWriter(String outputDir, String packageName, String fileName) {
        String targetDirPath = createPackageDirs(outputDir, packageName);
        String path = String.format("%s/%s.java", targetDirPath, fileName);
        try {
            return new BufferedWriter(new FileWriter(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
